import pygame, random, sys, math
from pygame.locals import *
from GameInfo import *
from DSLibrary import *
from Dijstras import *
from Tower import *
from Walker import *
from gg import *
debug = True
pygame.init()

if (debug): print("DEBUG MODE IS ON")

screen_size = (672,480)

screen = pygame.display.set_mode(screen_size)

pygame.display.set_caption("My First Tower Defense")

background = pygame.Surface(screen_size)

background.fill((255,255,255))
#wave = 1
pygame.mouse.set_visible(True)

random.seed()

timepassed = 0



grassImage = pygame.image.load("./gfx/gr32.png")
dirtImage = pygame.image.load("./gfx/dr32.png")
netherImage = pygame.image.load("./gfx/nether.png")

clock = pygame.time.Clock()

arena = [[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
         [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
         [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
         [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
         [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
         [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
         [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
         [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
         [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
         [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
         [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
         [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
         [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
         [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
         [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]]

width = 32
height = 32

startPos = None
endPos = None

towers = {}
botList = []
theMinPath = []

#lives = 5
#gold = 500
gi = Game()

gold = gi.gold
lives = gi.lives
wave = gi.wave

earn = None

debugCount = 0

font = pygame.font.SysFont("Tahoma", 15)
lfont = pygame.font.SysFont("Tahoma", 35)




##Construct grid
##for row in range(15):
##    arena.append([])
##    for column in range(21):
##        arena[row].append(0)ey

def endGame():
    gi = Game()


def checkWave():
    if (len(botList) == 0):
        nextWave()

def drawWaveText():
    waveText = lfont.render("Wave:" + str(gi.wave),1,(255,0,0))
    screen.blit(waveText, (screen_size[0]/2-waveText.get_size()[0]+50,screen_size[1]/2-waveText.get_size()[1]))
def nextWave():
    #global wave
    if (startPos is not None and endPos is not None):
        gi.wave+=1
        
        for i in range(gi.wave+1):
                botList.append(Walkers(theMinPath[i],screen,theMinPath[i:]))
        #pygame.time.delay(2000)
        gi.setPause = (2000)
        

def drawInfo():
    lGold = font.render("Gold:" + str(gold), 1, (255,255,0))
    lLives = font.render("Lives:" + str(lives), 1, (0,255,0))
    screen.blit(lGold, (500, 5))
    screen.blit(lLives, (585,5))


    
def drawArena():
    for row in range(15):
        for column in range(21):
            if arena[row][column]==5:
                pygame.draw.rect(screen,(0,0,255),(width*column,height*row,width,height),5)
                screen.blit(netherImage,Rect(width*column,height*row,width,height))
            elif arena[row][column]==6:
                pygame.draw.rect(screen,(255,0,0),(width*column,height*row,width,height),5)
                screen.blit(netherImage,Rect(width*column,height*row,width,height))
            elif arena[row][column]==15:
                #pygame.draw.rect(screen,(153,153,204),(width*column,height*row,width,height))
                screen.blit(dirtImage,Rect(width*column,height*row,width,height))
            else:
                #pygame.draw.rect(screen,(158,255,255),(width*column,height*row,width,height),2)
                screen.blit(grassImage,Rect(width*column,height*row,width,height))

def drawTowers():
    for i in towers:
        towers[i].drawTower()
        if towers[i].rect.collidepoint(pygame.mouse.get_pos()):
            towers[i].drawRange()

def attTarget():
    m = False
    for i in towers:
        if len(botList) != 0:
            for b in botList:
                if towers[i].radius + 16 >= math.sqrt((towers[i].center[0]-b.center[0])**2 + (towers[i].center[1]-b.center[1])**2):
                    towers[i].detectEnemy(b.center)
                    b.receiveDmg(towers[i].attack)
                    if b.hp <= 0:
                        botList.remove(b)
                        m = True
                        return m

#To draw path by assigning the coord. to arenna.
def assignPath():
    if theMinPath != [] or theMinPath is not None:
        for i in range(1,(len(theMinPath)-1)):
            coor = theMinPath[i]           
            x = coor[0]
            y = coor[1]
            arena[y][x] = 15


while True:
    mouse_x, mouse_y = pygame.mouse.get_pos()[0],pygame.mouse.get_pos()[1]

    for event in pygame.event.get():
        if (event.type == QUIT):
            pygame.quit()
            sys.exit()

        elif (event.type == MOUSEBUTTONDOWN):
            if (event.button == 3):
                pygame.quit()
                sys.exit()
            elif (event.button == 1):
                
                if startPos == None:        ##Initiate Starting pos
                    sPos_X = pygame.mouse.get_pos()[0]//32
                    sPos_Y = pygame.mouse.get_pos()[1]//32
                    startPos = Vertex((sPos_X,sPos_Y),None,(0,0,240),None)
                    arena[sPos_Y][sPos_X] = 5
                    print("Start Pos : ", startPos)
                    
                elif endPos == None:        ##Initiate Destination pos
                    ePos_X = pygame.mouse.get_pos()[0]//32
                    ePos_Y = pygame.mouse.get_pos()[1]//32
                    endPos = Vertex((ePos_X,ePos_Y),None,(0,240,0),None)
                    arena[ePos_Y][ePos_X] = 6
                    print("End Pos : ", endPos)
                    
                else:              

                    ##To build Towers
                    column = pygame.mouse.get_pos()[0]//32
                    row = pygame.mouse.get_pos()[1]//32
                    if arena[row][column] == 0:
                        if (gold-100) >= 0 :
                            towers[(row,column)] = Tower(Rect(column*32,row*32,32,32),screen)
                            arena[row][column] = 1
                            gold -= 100
                        else:
                            print("Insufficient Resources")
                    elif arena[row][column] == 1:
                        if (gold-200) >= 0:
                            towers[(row,column)].upgrade()
                            gold -= 200
                    else:
                        print("Unable to build here")
        
    timepassed += clock.tick()#FPS
    screen.blit(background, (0,0))
    if (startPos is not None and endPos is not None):
        theMinPath = givePath(arena,startPos.getId(),endPos.getId())
        assignPath()

    
    #if theMinPath != None and botList == [] and startPos != None and endPos != None:
        
    checkWave()     
    drawArena()
    drawTowers()
    drawInfo()
    

    if timepassed >= 280:
        earn = attTarget()
        if earn == True:
            gold += 100
            earn = False

    if timepassed >= 300 and botList != []:
        for bot in botList:
            bot.updatePos()
##        if botList[0].pathIndex > 1:
##            botList[1].updatePos()
##        if botList[0].pathIndex > 2:
##            botList[2].updatePos()
##        if botList[0].pathIndex > 4:
##            botList[3].updatePos()
##            botList[4].updatePos()
        print(gold,lives)
        timepassed = 0
        
    if botList != []:
        for b in botList:
            b.drawWalker()
            if b.pathIndex == len(b.path):
                lives -= 1
                botList.remove(b)

    
    if (gi.setPause > 0): drawWaveText()
    pygame.display.update()
    if (gi.setPause > 0):
        pygame.time.delay(gi.setPause)
        gi.setPause = 0
    

##want walkers to learn how to avoid towers
##let walkers find shortest path
    ##learn graphs













    
